package com.attcatstudy.sync;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

/**
 * @author attcat
 * ---做一个有趣的程序员
 * @date 2022-11-07 20:27
 * @description
 *
 * * 测试 偏向锁，轻量级锁，重量级锁标记变化
 * 关闭延迟开启偏向锁： -XX:BiasedLockingStartupDelay=0
 * 无锁 001
 * 偏向锁 101
 * 轻量级锁 00
 * 重量级锁 10
 *
 *
 */
@Slf4j
public class LockEscalationDemo {
    public static void main(String[] args) throws InterruptedException {
        log.debug(ClassLayout.parseInstance(new Object()).toPrintable());
        Thread.sleep(4000);
        Object obj = new Object();

        new Thread(new Runnable() {
            @Override
            public void run() { log.debug(Thread.currentThread().getName()+"开始执行。。。\n" +ClassLayout.parseInstance(obj).toPrintable());
                synchronized (obj){
                    //obj.hashCode();//当对象正处于偏向锁时，调用HashCode将使偏向锁强制升级成重量锁
                    //                    obj.notify();// 会升级为轻量级锁 00

                    //obj.wait(100);//会升级为重量级锁

                    log.debug(Thread.currentThread().getName()+"获取锁执行中。。。\n" +ClassLayout.parseInstance(obj).toPrintable());


                }
                log.debug(Thread.currentThread().getName()+"释放锁。。。\n" +ClassLayout.parseInstance(obj).toPrintable());
            }
        },"thread1").start();

//控制线程竞争时机
//        Thread.sleep(3);
        new Thread(new Runnable() {
            @Override
            public void run() { log.debug(Thread.currentThread().getName()+"开始执行。。。\n" +ClassLayout.parseInstance(obj).toPrintable());
                synchronized (obj){
                    log.debug(Thread.currentThread().getName()+"获取锁执行中。。。\n" +ClassLayout.parseInstance(obj).toPrintable());

                }
                log.debug(Thread.currentThread().getName()+"释放锁。。。\n" +ClassLayout.parseInstance(obj).toPrintable());
            }
        },"thread2").start();




        Thread.sleep(5000);
        log.debug(ClassLayout.parseInstance(obj).toPrintable());
    }

}
